#!/usr/bin/python3
# -*- encoding: utf-8 -*-
import sys


def conversion_line(text: str) -> str:
    '''
    input:
    ( float float float ) ( float float float ) ( float float float ) str [ float float float float ] [ float float float float ] float float float
    output:
    ( float float float ) ( float float float ) ( float float float ) ( ( 0.0004882812 0 -0 ) ( -0 0.0006510417 0 ) ) str float float float
    '''
    result = ''
    tmp = ''
    # 使用)分割,先将不用处理的部分加入结果
    for i in text.split(')'):
        # 如果是字符串,则直接加入结果
        if '(' in i:
            result += i + ')'
        else:
            tmp += i
    # 记录str
    str_tmp = tmp.split('[', 1)[0].strip()
    # 最后3位float float float
    # float_tmp2 = tmp.split(']')[-1].split(' ')
    # str_tmp2 = ''.join(' ' + str(int(float(t))) for t in float_tmp2 if t)
    str_tmp2 = ' 0 0 0'
    result += " ( ( 0.0004882812 0 -0 ) ( -0 0.0006510417 0 ) ) " + str_tmp + str_tmp2
    return result


def conversion_block(text: str) -> str:
    result = ''
    # 按行遍历text,如果(开头则使用conversion_line处理
    for line in text.split('\n'):
        if line.startswith('('):
            result += conversion_line(line) + '\n'
        else:
            result += line + '\n'
    result = result.replace('{', '{\nbrushDef\n{').replace('}', '}\n}')
    return result


def conversion(text: str) -> str:
    result = ''
    tmp = ''
    # 按行遍历text
    for line in text.split('\n'):
        # 如果tmp不是空且碰到了'{'则将tmp写出
        if tmp and '{' in line:
            result += tmp
            tmp = ''
        # 放入缓存区
        tmp += line + '\n'
        # 如果遇到了}且tmp中包含(,则将tmp放入conversion_block处理后写出
        if '}' in line and '(' in tmp:
            result += conversion_block(tmp)
            tmp = ''
    # 遍历结束将最后的tmp写出
    result += tmp
    # 移除空行
    result = '\n'.join([i for i in result.split('\n') if i])
    return result


def main():
    # 遍历参数
    args = sys.argv[1:]
    if '--help' in args:
        print(f'{sys.argv[0]} input.map output.map')
    else:
        try:
            input_path = args[0]
            output_path = args[1]
        except IndexError:
            print(f'usage:{sys.argv[0]} input.map output.map')
            return
        with open(input_path, 'r') as f:
            text = f.read()
        text = conversion(text)
        with open(output_path, 'w') as f:
            f.write(text)


if __name__ == '__main__':
    main()
